import threading
import time
import json
from fastapi import FastAPI ,WebSocket , Request
from apilib.component import compManager,TComp


class TTsComp:
    def __init__(self):
        self.code = ""
        self.tsCompType = ""
        self.info = {}
        self.tag = {}
        self.status = {}
        self.actionHandlers ={}
        self.eventHandlers={
            "init":None,
            "changed":None
        }
        self.sysTime = 0
        self.clockTime = 0
    def log(self , data ):
        try:
            print( self.code , 'error', data)
        except Exception as er:
            print(er)
    def triggerEvent(self , eventCode , eventData={} ):
        try:
            if eventCode in self.eventHandlers.keys():
                eventArgs ={
                    "code": eventCode ,
                    "sender": self ,
                    "data": eventData
                }
                self.eventHandlers[eventCode](  eventArgs)
        except Exception as er:
            self.log(er)
    def updateStatus(self ):
        try:
            pass
        except Exception as er:
            self.log(er)
        return  self.status
    def getSysClockTime(self ):
        res = 0
        try:
            res = time.time() - self.sysTime + self.clockTime
        except Exception as er:
            self.log(er)
        return  res
    def log(self , data ):
        try:
            print( self.code , 'error', data)
        except Exception as er:
            print(er)
    def acReset(self):
        try:
            self.triggerEvent('init')
        except Exception as er:
            self.log(er)

class TTsClock(TTsComp):
    def __init__(self):
        super().__init__()
        self.tsCompType = "TTsClock"
        self.interval = 0
        self.triggerIntervalEvent = 0
        self.thresholds = {
                "end": {
                    "code": "end",
                    "threshold": 45,
                    "reverse": 0,
                    "autoStop": 1,
                    "trigged":0
                }
            }
        self.info = {
            "start": 0,
            "end": 0,
            "pauseList": []
        }
        self.eventHandlers['interval'] = None
        self.eventHandlers['timeout'] = None
        self.actionHandlers = {
            "acReset" : self.acReset,
            "acSetClockTime" : self.acSetClockTime,
            "acStart" : self.acStart,
            "acEnd" : self.acEnd,
            "acPauseSwitch" : self.acPauseSwitch
        }

    def updateStatus(self):
        try:
            actived = self.info['start'] > 0 and self.info['end'] == 0
            started = self.info['start'] > 0
            ended = self.info['end'] > 0
            paused = len(self.info['pauseList']) % 2 == 1
            endTime = self.info['end']  if self.info['end'] >0 else self.getSysClockTime()
            runTime = endTime - self.info['start'] if self.info['start'] > 0 else 0
            pauseTime = self.getPauseTime()
            netTime = runTime - pauseTime
            self.status = {
                "type": "clock",
                "code": self.code,
                "start": self.info['start'],
                "end": self.info['end'],
                "actived": actived,
                "started": started,
                "ended": ended,
                "paused": paused,
                "runTime": runTime,
                "pauseTime": pauseTime,
                "netTime": netTime
            }
            for th  in self.thresholds.values():
                k1 = f"thresholds_{th['code']}_threshold"
                v1 = th['threshold']
                k2 = f"thresholds_{th['code']}_reverse"
                v2 = th['reverse']
                k3 = f"thresholds_{th['code']}_current"
                v3 = th['threshold'] - netTime
                k4 = f"thresholds_{th['code']}_timeout"
                v4 =  0 if  th['threshold'] >= netTime else netTime - th['threshold']
                self.status[k1] = v1
                self.status[k2] = v2
                self.status[k3] = v3
                self.status[k4] = v4
        except Exception as er:
            self.log(er)
        return self.status

    def acReset(self):
        try:
            self.info ={
                "start": 0,
                "end": 0,
                "pauseList": []
            }
            self.triggerEvent('init')
        except Exception as er:
            self.log(er)

    def acSetClockTime(self, acTime):
        try:
            self.sysTime = time.time()
            self.clockTime = acTime
        except Exception as er:
            self.log(er)

    def acStart(self, acTime):
        try:
            self.sysTime = time.time()
            self.clockTime = acTime

            self.info['start'] = acTime
            self.info['end'] = 0
            self.info['pauseList'].clear()
            self.triggerEvent("changed", {"ac": "acStart"})
            if self.interval > 0:
                (threading.Thread(target=self.loopExecute, daemon=True)).start()
        except Exception as er:
            self.log(er)

    def acEnd(self, acTime):
        try:
            self.sysTime = time.time()
            self.clockTime = acTime
            self.info['end'] = acTime
            if (len(self.info['pauseList']) % 2 == 1):
                self.info['pauseList'].append(acTime)
            self.triggerEvent("changed", {"ac": "acEnd"})
        except Exception as er:
            self.log(er)

    def acPauseSwitch(self, acTime):
        try:
            self.sysTime = time.time()
            self.clockTime = acTime
            self.info['pauseList'].append(acTime)
            self.triggerEvent("changed", {"ac": "acPauseSwitch"})
        except Exception as er:
            self.log(er)

    def isActived(self):
        res = False
        try:
            res = self.info['start'] > 0 and self.info['start'] == 0
        except Exception as er:
            self.log(er)
        return res

    def getPauseTime(self):
        pauseTime = 0
        try:
            pauseNums = len(self.info['pauseList'])
            if pauseNums > 0:
                for i in range(pauseNums):
                    if i % 2 == 0:
                        pauseTime = pauseNums - self.info['pauseList']
                    else:
                        pauseTime = pauseNums + self.info['pauseList']
                if pauseNums % 2 == 1:
                    pauseTime = pauseTime + time.time() - self.sysTime + self.clockTime
        except Exception as er:
            self.log(er)
        return pauseTime

    def getNetTime(self):
        res = 0
        try:
            if self.info['start'] > 0:
                pasuseTime = self.getPauseTime()
                endTime = self.info['end']  if self.info['end'] > 0 else self.getSysClockTime()
                res = endTime - self.info['start'] - pasuseTime
        except Exception as er:
            self.log(er)
        return res

    def loopExecute(self):
        try:
            actived = self.isActived()
            interval = self.interval
            while actived:
                try:
                    if self.triggerIntervalEvent>0 :
                        self.triggerEvent('interval')
                    netTime = self.getNetTime()
                    for thresholdItem in self.thresholds.values():
                        if thresholdItem['trigged']==0:
                            timeout = thresholdItem['threshold'] > 0 and netTime > thresholdItem['threshold']
                            if timeout :
                                if self.triggerIntervalEvent>0   :
                                    params = {
                                        "thresholdItem": thresholdItem,
                                        "netTime": netTime
                                    }
                                    self.triggerEvent('timeout', params)
                                    thresholdItem['trigged'] == 1
                                if thresholdItem['autoStop']:
                                    break
                    time.sleep(interval)
                    actived = self.isActived()
                except Exception as err:
                    self.log(err)
            atm = self.getSysClockTime()
            self.acEnd(atm)
        except Exception as er:
            self.log(er)

class TTsGate(TTsComp):
    def __init__(self):
        super().__init__()
        self.tsCompType = "TTsGate"
        self.info = {
            "passTime": 0,
            "passLog": []
        }
        self.actionHandlers = {
            "acReset" : self.acReset,
            "acPass" : self.acPass
        }

    def  updateStatus(self):
        try:
            self.status = {
                "type": "gate",
                "code": self.code,
                "passTime": self.info['passTime'],
                "passLog": self.info['passLog'],
                "passNum": len(self.info['passLog'])
            }
        except Exception as er:
            self.log(er)
        return self.status

    def acReset(self):
        try:
            self.info = {
                "passTime": 0,
                "passLog": []
            }
            self.triggerEvent('init')
        except Exception as er:
            self.log(er)

    def acPass(self, acTime):
        try:
            self.sysTime = time.time()
            self.clockTime = acTime
            self.info['passTime'] = acTime
            self.info['passLog'].append(acTime)
            self.triggerEvent('changed',self.info)
        except Exception as er:
            self.log(er)

class TTsPoint(TTsComp):
    def __init__(self):
        super().__init__()
        self.order = 0
        self.tsCompType = "TTsPoint"
        self.info = {
            "passTime": 0,
            "refuseTime": 0,
            "status": 0
        }
        self.actionHandlers = {
            "acReset" : self.acReset,
            "acSetStatus" : self.acSetStatus
        }

    def  updateStatus(self):
        try:
            self.status = {
                "type": "point",
                "code": self.code,
                "order": self.order,
                "passTime": self.info['passTime'],
                "refuseTime": self.info['refuseTime'],
                "status": self.info['status'],

                "passed": self.info['status'] > 0,
                "success" :  self.info['status']==1,
                "fail" :  self.info['status']==2,
                "refuse" :  self.info['refuseTime']>0
            }
        except Exception as er:
            self.log(er)
        return self.status

    def acReset(self):
        try:
            self.info = {
                "passTime": 0,
                "refuseTime": 0,
                "status": 0
            }
            self.triggerEvent('init')
        except Exception as er:
            self.log(er)

    def acSetStatus(self, acTime , status):
        try:
            self.sysTime = time.time()
            self.clockTime = acTime
            if status == 0 :
                self.info['status'] = 0
                self.info['passTime'] = 0
            elif status in [1,2] :
                self.info['status'] = status
                self.info['passTime'] = acTime
            elif status == 3 :
                self.info['refuseTime'] = acTime
            self.triggerEvent('changed')
        except Exception as er:
            self.log(er)

class TTsWsSessions :
    def __init__(self):
        self.code = "wsSessions"
        self.tsCompType = "TTsWsSessions"
        self.sessions ={}
        self.eventHandlers={
            "onSessionChanged": None,
            "onMessage": None
        }
    async def acceptWs(self , websocket: WebSocket):
        try:
            await websocket.accept()
            wsId = str(websocket)[1:-1].split(' ')[-1]
            while True:
                try:
                    time.sleep(0.01)
                    success , msg = await self.readMsg(websocket)
                    if success :
                        if msg['ac'] =='regist':
                            self.sessions[wsId] = {
                                "wsId": wsId,
                                "peerId": msg['data']['peerId'],
                                "peerType": msg['data']['peerType'],
                                "subAcs": msg['data']['subAcs'],
                                "ws": websocket,
                                "registTime": time.time()
                            }
                            self.doOnSessionChanged()
                        else:
                            self.doOnMsg(msg)
                    else:
                        if wsId in self.sessions.keys():
                            del self.sessions[wsId]
                        try:
                            await websocket.close(1001 , 'message error')
                        except Exception as errClose:
                            print('websocket.close error.' , errClose)
                        self.doOnSessionChanged()
                        break
                except Exception as erRead:
                    print('wsAccept read' , erRead)
        except Exception as er:
            print('wsAccept',er)
    async def readMsg(self , websocket: WebSocket):
        res = {}
        success = False
        try:
            wsState = str( websocket.client_state)
            if wsState  == 'WebSocketState.CONNECTED' :
                recData = await websocket.receive_text()
                try:
                    msg = json.loads(recData)
                    success = "ac" in msg.keys() and "data" in msg.keys()
                    if success :
                        res = msg
                except Exception as erDecode:
                    print(erDecode , 'decoder')
        except Exception as er:
            print('wsAccept readMsg',er)
        return  success , res
    def getPeersMsg(self):
        return {
            "ac":"peerChanged",
            "data":self.getOnlineSessions()
        }
    def getOnlineSessions(self):
        return [
                {
                    "wsId": s["wsId"],
                    "peerId": s['peerId'],
                    "peerType": s['peerType'],
                    "subAcs": s['subAcs'],
                    "registTime": s["registTime"]
                }
                for s in self.sessions.values()
            ]
    def doOnSessionChanged(self):
        if self.eventHandlers['onSessionChanged'] != None:
            try:
                evArgs = {
                    "eventCode": "onSessionChanged",
                    "eventSender": self,
                    "sessions": self.getPeersMsg()
                }
                self.eventHandlers['onSessionChanged'](evArgs)
            except Exception as eer:
                print(eer)
    def doOnMsg(self , msg):
        if self.eventHandlers['onMessage']!=None:
            try:
                evArgs = {
                    "code": "onMessage",
                    "sender": self,
                    "data": msg
                }
                self.eventHandlers['onMessage'](evArgs)
            except Exception as erAc:
                print("acceptWs event error" , erAc)
    async def sendMsg(self , msg):
        res = {}
        success = False
        try:
            if 'ac' in msg.keys():
                content = json.dumps(msg , ensure_ascii=False)
                recWs =[
                    s['ws']
                    for s in self.sessions.values()
                    if msg['ac'] in  s['subAcs']
                ]
                for ws in recWs:
                    try:
                        wsState = str(ws.client_state)
                        if wsState == 'WebSocketState.CONNECTED':
                            await ws.send_text(content)
                    except Exception as sendErr:
                        print('send msg err' , sendErr)
        except Exception as er:
            print('ws regist',er)
        return  success , res

class TPluginTsEqu(TComp):
    def __init__(self):
        super().__init__()
        self.compSettings={}
        self.handlers={
            "action" : self.action,
            "tsReset" : self.tsReset,
            "getInfo": self.getInfo,
            "getCompStatus": self.getCompStatus,
            "getTsStatus": self.getTsStatus
        }
        self.eventHandler ={
            "action": self.action,
            "getCompInfo": self.getCompInfo,
            "getInfo": self.getInfo,
            "getCompStatus": self.getCompStatus,
            "getTsStatus": self.getTsStatus
        }
        self.signalLog=[]

        self.tsType = ""
        self.pointNum = 12
        self.penPoint = 4
        self.penRefuse = 4
        self.penSecond = 1
        self.clocks={}
        self.gates={}
        self.points= []
        self.tsComps ={}
        self.ws = TTsWsSessions()
    def compInit(self):
        try:
            super().compInit()
            self.tsInit()
        except Exception as eer:
            self.manager.log(eer)
    def log(self , data ):
        try:
            print( self.code , 'error', data)
        except Exception as er:
            print(er)
    def tsInit(self):
        try:
            self.tsType = self.compSettings['tsType']
            self.pointNum = self.compSettings['pointNum']
            self.penPoint = self.compSettings['penPoint']
            self.penRefuse = self.compSettings['penRefuse']
            self.penSecond = self.compSettings['penSecond']
            for clockKey in self.compSettings['clocks'].keys():
                clockItem = self.compSettings['clocks'][clockKey]
                clock = TTsClock()
                clock.code = clockKey
                clock.interval = clockItem['interval']
                clock.thresholds = clockItem['thresholds']
                self.tsComps[clock.code] = clock
                self.clocks[clock.code] = clock
            for gateKey in self.compSettings['gates'].keys():
                gateItem = self.compSettings['gates'][gateKey]
                gate = TTsGate()
                gate.code = gateKey
                self.tsComps[gateKey] = gate
                self.gates[gateKey] = gate
            for i in range(self.pointNum):
                point = TTsPoint()
                point.order = i+ 1
                point.code = f"tsPoint_{point.order}"
                self.tsComps[point.code] = point
                self.points.append(point)

            for comp in self.tsComps.values():
                for evKey in comp.eventHandlers.keys():
                    comp.eventHandlers[evKey] = self.doOnEvent
                for handlerKey in comp.actionHandlers.keys():
                    acKey = comp.code +"_"+handlerKey
                    handler = comp.actionHandlers[handlerKey]
                    self.handlers[acKey] = handler

            if self.ws!=None:
                self.ws.eventHandlers['onMessage'] = self.doOnEvent

        except Exception as er:
            self.log(er)
    def tsSetEvents(self):
        try:
            pass
        except Exception as er:
            self.log(er)
    def tsReset(self):
        try:
            for comp in self.tsComps.values():
                try:
                    comp.acReset()
                except Exception as eer:
                    self.log(eer)

        except Exception as er:
            self.log(er)
        return  self.getTsStatus(1)
    def doOnEvent(self ,eventData):
        try:
            pass
        except Exception as err:
            self.log(err)
    def doOnSetStatus(self , resStatus):
        try:
            pass
        except Exception as err:
            self.log(err)
    def getCompInfo(self , tsCompCode ):
        res ={}
        try:
            if tsCompCode in self.comps.keys():
                comp = self.comps[tsCompCode]
                res = comp.info
        except Exception as err:
            self.log(err)
        return res
    def getInfo(self ):
        res ={
            "clocks":{},
            "gates":{},
            "points":[]
        }
        try:
            for tsCompCode in self.tsComps.keys():
                comp = self.tsComps[tsCompCode]
                info = comp.info
                if comp.tsCompType == 'TTsClock':
                    res["clocks"][comp.code] = info
                elif comp.tsCompType == 'TTsGate':
                    res["gates"][comp.code] = info
                if comp.tsCompType == 'TTsPoint':
                    res["points"].append(info)
        except Exception as err:
            self.log(err)
        return res
    def getCompStatus(self , tsCompCode , updateFlag = 0 ):
        res ={}
        try:
            if tsCompCode in self.comps.keys():
                comp = self.comps[tsCompCode]
                if updateFlag>0:
                    comp.updateStatus()
                res = comp.status
        except Exception as err:
            self.log(err)
        return res
    def getTsStatus(self  , updateFlag = 0 ):
        res ={
            "clocks": {},
            "gates": {},
            "points": [],
            "enables":{},
            "statics":{}
        }
        t0= time.time()
        try:
            for tsCompCode in self.tsComps.keys():
                comp = self.tsComps[tsCompCode]
                status = comp.status if updateFlag==0 else  comp.updateStatus()
                if comp.tsCompType == 'TTsClock':
                    res["clocks"][comp.code] = status
                elif comp.tsCompType == 'TTsGate':
                    res["gates"][comp.code] = status
                if comp.tsCompType == 'TTsPoint':
                    res["points"].append(status)
            self.doOnSetStatus(res)
        except Exception as err:
            self.log(err)
        t1= time.time()

        print(f'update status :{t1-t0}')
        return res
    def wxNotifyChanged(self , sender , notifyKey='' , tag ={}):
        try:
            if self.ws!=None :
                notifyMsg = {
                    "ac":"notify",
                    "data":{
                        "key": notifyKey,
                        "senderCode": sender.code,
                        "senderType": sender.tsCompType ,
                        "tag":tag
                    }
                }
                print(notifyMsg)
        except Exception as err:
            self.log(err)
    async def wxNotifyChanged_send(self , sender , notifyKey='' , tag ={}):
        try:
            if self.ws!=None :
                notifyMsg = {
                    "ac":"notify",
                    "data":{
                        "key": notifyKey,
                        "senderCode": sender.code,
                        "senderType": sender.tsType ,
                        "tag":tag
                    }
                }
                await self.ws.sendMsg(notifyMsg)
        except Exception as err:
            self.log(err)

class TPluginTsEqu_01(TPluginTsEqu):
    def __init__(self):
        super().__init__()
    def doOnEvent(self ,eventData):
        try:
            evCode = eventData['code']
            sender = eventData['sender']
            evData = eventData['data']

            preClock = self.clocks['pre']
            gameClock = self.clocks['game']

            if sender.code == 'wsSessions':
                if evCode =='onSessionChanged':
                    if self.ws!=None :
                        self.wxNotifyChanged( sender ,'sessionChanged', self.ws.getOnlineSessions())
                elif evCode =='onMessage':
                    ac = evData['ac']
                    if ac in ['RT', "C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8"]:
                        tm = evData['data']['t']
                        if preClock.info['end']==0 :
                            preClock.acSetClockTime(tm)
                        if gameClock.info['end']==0 :
                            gameClock.acSetClockTime(tm)
                        if ac !="RT":
                            self.doOnSignal( ac , tm )
            elif sender.code == 'pre':
                if evCode =='init':
                    self.wxNotifyChanged( sender ,'init' )
                elif evCode =='changed':
                    self.wxNotifyChanged( sender ,'chanegd'  )
                elif evCode =='interval':
                    pass
                elif evCode =='timeout':
                    self.wxNotifyChanged( sender ,'timeout'  )
                    if preClock.info['end']==0:
                        tm = gameClock.getSysClockTime()
                        preClock.acEnd(tm)
                    if gameClock.info['start']==0:
                        tm = gameClock.getSysClockTime()
                        gameClock.acStart(tm)
            elif sender.code == 'game':
                if evCode =='init':
                    self.wxNotifyChanged( sender ,'init' )
                elif evCode =='changed':
                    self.wxNotifyChanged( sender ,'chanegd'  )
                elif evCode =='interval':
                    pass
                elif evCode =='timeout':
                    self.wxNotifyChanged( sender ,'timeout'  )
            elif sender.code == 'startGate':
                if evCode =='init':
                    self.wxNotifyChanged( sender ,'init' )
                elif evCode =='changed':
                    self.wxNotifyChanged( sender ,'chanegd'  )
                    startGate = self.gates['startGate']
                    if startGate.info['passTime']>0 :
                        if gameClock.info['start'] == 0:
                            tm = gameClock.getSysClockTime()
                            gameClock.acStart(tm)

            elif sender.code == 'finishGate':
                if evCode =='init':
                    self.wxNotifyChanged( sender ,'init' )
                elif evCode =='changed':
                    self.wxNotifyChanged( sender ,'chanegd'  )
                    finishGate = self.gates['finishGate']
                    if finishGate.info['passTime']>0 :
                        if gameClock.info['end'] == 0:
                            nums = [x for x in self.points if x.info['passTime']==0]
                            if nums ==0 :
                                tm = gameClock.getSysClockTime()
                                gameClock.acEnd(tm)
            elif sender.code[:8] == 'tsPoint_':
                if evCode =='init':
                    pass
                elif evCode =='changed':
                    self.wxNotifyChanged( sender ,'chanegd'  )
        except Exception as err:
            self.log(err)
    def doOnSetStatus(self , resStatus):
        try:
            preClock = self.clocks['pre']
            gameClock = self.clocks['game']
            startGate = self.gates['startGate']
            finishGate = self.gates['finishGate']

            preStart = preClock.info['start'] ==0
            prePause = preClock.info['start']>0 and preClock.info['end']==0 and len(preClock.info['pauseList']) %2 ==0
            preResume = preClock.info['start']>0 and preClock.info['end']==0 and len(preClock.info['pauseList']) %2 ==1
            preEnd = preClock.info['start'] >0 and preClock.info['start'] ==0

            gameStart = gameClock.info['start'] ==0 and preClock.info['start'] >0
            gamePause = gameClock.info['start']>0 and gameClock.info['end']==0 and len(gameClock.info['pauseList']) %2 ==0
            gameResume = gameClock.info['start']>0 and gameClock.info['end']==0 and len(gameClock.info['pauseList']) %2 ==1
            gameEnd = gameClock.info['start'] >0 and gameClock.info['start'] ==0 and len(
                [
                    x for x in self.points if x['passTime']==0
                ])==0

            gateStartPass = gameStart
            finishStartPass = gameEnd
            enables={
                "preStart": preStart ,
                "prePause": prePause ,
                "preResume": preResume ,
                "preEnd": preEnd ,
                "gameStart": gameStart ,
                "gamePause": gamePause ,
                "gameResume": gameResume ,
                "gameEnd": gameEnd ,
                "gateStartPass": gateStartPass ,
                "gateFinishPass": finishStartPass ,
            }
            netTime = gameClock.getNetTime()
            threshold = gameClock.thresholds["end"]['threshold']
            gameTimeout = 0 if threshold>netTime else netTime-threshold
            statics={
                "gameTimeout":gameTimeout ,
                "failNum":len([x for x in self.points if x.info['status']==2]) ,
                "refuseNum":len([x for x in self.points if x.info['refuseTime']>0])
            }
            resStatus['enables'] = enables
            resStatus['statics'] = statics
        except Exception as err:
            self.log(err)
    def doOnSignal(self , signalCode , acTime):
        try:
            preClock = self.clocks['pre']
            gameClock = self.clocks['game']
            gateStart = self.gates['start']
            gateFinish = self.gates['finish']
            tm = gameClock.getSysClockTime()
            if signalCode =='C0':
                if preClock.info['start']>0 and gameClock.info['start']==0 :
                    gateStart.acPass(tm)
            elif signalCode =='C1':
                if preClock.info['start']>0:
                    preClock.acStart(tm)
                elif gameClock.info['start']>0 and gameClock.info['end']==0:
                    gameClock.acPauseSwitch(tm)
                elif gameClock.info['start']==0 and preClock.info['start']>0 and preClock.info['end']==0:
                    preClock.acPauseSwitch(tm)
            elif signalCode =='C2':
                nums = len([
                    x for x in self.points if x['passTime']==0
                ])
                if gameClock.info['start']>0 and gameClock.info['end']==0 and nums==0:
                    gateFinish.acPass(tm)
            elif signalCode =='C3':
                self.signalLog.append({
                    "signalCode": signalCode ,
                    "time":tm
                })
            elif signalCode =='C4':
                pass
            elif signalCode =='C5':
                pass
            elif signalCode =='C6':
                pass
            elif signalCode =='C7':
                pass
            elif signalCode =='C8':
                pass
        except Exception as err:
            self.log(err)


_tsSettings = {
    "tsType":"equts_01" ,
    "tsDesc":"不同比赛类型的描述",
    "pointNum": 12,
    "penPoint":4,
    "penRefuse":4,
    "penSecond":1,
    "clocks":{
        "pre":{
            "interval":0.1,
            "thresholds":{
                "end": {
                    "code": "end",
                    "threshold": 45,
                    "reverse": 0,
                    "autoStop": 1,
                    "trigged":0
                }
            }
        },
        "game":{
            "interval":0.1,
            "thresholds":{
                "end": {
                    "code": "end",
                    "threshold": 81,
                    "reverse": 0,
                    "autoStop": 0,
                    "trigged":0
                }
            }
        }
    },
    "gates":{
        "startGate":{},
        "finishGate":{}
    }
}
_tsSettings_t01= json.loads(json.dumps(_tsSettings,ensure_ascii=False))
_tsSettings_t01['tsDesc'] = "全国赛模式.45秒倒计时，时间到自动启动比赛计时。一个起点，1个终点,12个障碍，依次通过障碍"

compManager.registComponentType('TPluginTsEqu_01' , TPluginTsEqu_01 , _tsSettings_t01)

